//
//  FWTitleView.swift
//  DBS
//
//  Created by 王方伟 on 2017/4/18.
//  Copyright © 2017年 wfw. All rights reserved.
//

import UIKit

private let kScrollLineH : CGFloat = 2

protocol TitleViewDelegate : class{
    func onClickTitleView(_ titleView : FWTitleView, from : NSInteger, to : NSInteger)
}

class FWTitleView: UIView {
    // MARK: 对外属性
    weak var delegate : TitleViewDelegate?
    
    fileprivate var titles:[String]
    fileprivate var style:FWTitleStyle
    fileprivate var titleLabels : [UILabel] = [UILabel]()
    fileprivate var currentIndex : NSInteger = 0
    fileprivate lazy var scrollView : UIScrollView = {
        let scrollView = UIScrollView(frame: self.bounds)
        scrollView.showsHorizontalScrollIndicator = false
        return scrollView
    }()
    
    
    fileprivate lazy var scrollLine : UIView = {
        let scrollLine = UIView()
        scrollLine.backgroundColor = UIColor.orange
        return scrollLine
    }()
    
    init(frame: CGRect, titles:[String], style:FWTitleStyle) {
        self.titles = titles;
        self.style = style
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension FWTitleView {
    fileprivate func setupUI(){
        addSubview(scrollView)
        setupTitleLable()
        setupTitleLableFrame()
        setupBottomLineAndScrollLine()
    }
    
    private func setupTitleLable(){
        for (index, title) in titles.enumerated() {
            let lable = UILabel()
            lable.text = title
            lable.textAlignment = .center
            lable.font = UIFont.systemFont(ofSize: style.fontSize)
            lable.textColor = (index == 0 ? style.selectColor : style.normalColor)
            lable.tag = index
            lable.isUserInteractionEnabled = true
            let tapGR = UITapGestureRecognizer(target: self, action: #selector(onClickLable(_:)))
            lable.addGestureRecognizer(tapGR)
            scrollView.addSubview(lable)
            titleLabels.append(lable)
        }
    }
    
    private func setupTitleLableFrame(){
        let count = titles.count
        for (index, label) in titleLabels.enumerated() {
            var w : CGFloat = 0
            let h = bounds.height
            var x : CGFloat = 0
            let y : CGFloat = 0
            
            if style.isScrollEnable {
                w = (titles[index] as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options:.usesLineFragmentOrigin, attributes: [NSFontAttributeName : label.font], context: nil).width
                if index == 0 {
                    x = style.itemMargin * 0.5
                }else{
                    let agoLabel = titleLabels[index - 1]
                    x = agoLabel.frame.maxX + style.itemMargin
                }
            }else{
                w = bounds.width / CGFloat(count)
                x = w * CGFloat(index)
            }
            
            label.frame = CGRect(x: x, y: y, width: w, height: h)
        }
        
        scrollView.contentSize = style.isScrollEnable ? CGSize(width: titleLabels.last!.frame.maxX + style.itemMargin * 0.5, height: 0) : CGSize.zero
    }
    
    
    private func setupBottomLineAndScrollLine() {
        // 1.添加底线
        let bottomLine = UIView()
        bottomLine.backgroundColor = UIColor.lightGray
        bottomLine.isHidden = !style.isShowBottomLine
        let lineH : CGFloat = 0.5
        bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
        addSubview(bottomLine)
        
        // 2.添加scrollLine
        // 2.1.获取第一个Label
        guard let firstLabel = titleLabels.first else { return }

        // 2.2.设置scrollLine的属性
        scrollView.addSubview(scrollLine)
        scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
    }
}

//MARK:TitleView点击事件
extension FWTitleView {
    @objc fileprivate func onClickLable(_ tapGR:UITapGestureRecognizer){
        // 0.获取当前Label
        guard let currentLabel = tapGR.view as? UILabel else { return }
        
        // 1.如果是重复点击同一个Title,那么直接返回
        if currentLabel.tag == currentIndex { return }
        
        // 2.获取之前的Label
        let oldLabel = titleLabels[currentIndex]
        
        // 3.切换文字的颜色
        currentLabel.textColor = style.selectColor
        oldLabel.textColor = style.normalColor
        
        // 4.保存最新Label的下标值
        currentIndex = currentLabel.tag
        
        // 5.通知代理
        delegate?.onClickTitleView(self, from: currentIndex, to: currentLabel.tag)
        
        // 6.居中显示
        contentViewDidEndScroll()
        
        // 7.调整bottomLine
        if style.isShowBottomLine {
            UIView.animate(withDuration: 0.3, animations: {
                self.scrollLine.frame.origin.x = currentLabel.frame.origin.x
                self.scrollLine.frame.size.width = currentLabel.frame.size.width
            })
        }

    }
    
    func contentViewDidEndScroll() {
        // 0.如果是不需要滚动,则不需要调整中间位置
        guard style.isScrollEnable else { return }
        
        // 1.获取获取目标的Label
        let targetLabel = titleLabels[currentIndex]
        
        // 2.计算和中间位置的偏移量
        var offSetX = targetLabel.center.x - bounds.width * 0.5
        if offSetX < 0 {
            offSetX = 0
        }
        
        let maxOffset = scrollView.contentSize.width - bounds.width
        if offSetX > maxOffset {
            offSetX = maxOffset
        }
        
        // 3.滚动UIScrollView
        scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true)
        
    }
}

//MARK:Content 代理
extension FWTitleView  {
    func onSlideContentView(from: NSInteger, to: NSInteger, progress: CGFloat) {
        // 1.取出sourceLabel/targetLabel
        let sourceLabel = titleLabels[from]
        let targetLabel = titleLabels[to]
        
        // 3.颜色的渐变(复杂)
        // 3.1.取出变化的范围
        let deltaRGB = UIColor.getRGBDelta(style.selectColor, style.normalColor)
        
        let selectRGB = style.selectColor.getRGB()
        let normalRGB = style.normalColor.getRGB()
        
        sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0 * progress, g: selectRGB.1 - deltaRGB.1 * progress, b: selectRGB.2 - deltaRGB.2 * progress)
        
        targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * progress, g: normalRGB.1 + deltaRGB.1 * progress, b: normalRGB.2 + deltaRGB.2 * progress)

        // 4.记录最新的index
        currentIndex = to
        let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
        let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width
        // 5.调整bottomLine
//        if style.isShowBottomLine {
//            UIView.animate(withDuration: 0.3, animations: {
//                self.scrollLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress
//                self.scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress
//            })
//        }
        
        if style.isShowBottomLine {
            scrollLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress
            scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress
        }

        
    }
}
